<?php
/**
 *   This file is part of GeoArticle (a Joomla plugin).
 *   Written by Ivar Bergman (www.ivarbergman.se)
 *   Copyright (c) 2010 Ivar Bergman. All rights reserved.
 *
 *   GeoArticle is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   GeoArticle is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with GeoArticle.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

  // Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.model');

class GeoArticleModelGeoArticle extends JModel
{
  var $_id = null;
  var $_data = null;

  function __construct()
  {
    parent::__construct();

    $array = JRequest::getVar('cid', array(0), '', 'array');
    $edit	= JRequest::getVar('edit',true);
        
    if($edit)
      $this->setId((int)$array[0]);
  }

  function setId($id)
  {
    // Set record id and wipe data
    $this->_id		= $id;
    $this->_data	= null;
  }

  function &getData()
    {
      // Load the record data
      if (!$this->_loadData())
	$this->_initData();

      return $this->_data;
    }

  function isCheckedOut( $uid=0 )
  {
    if ($this->_loadData())
      {
	if ($uid) {
	  return ($this->_data->checked_out && $this->_data->checked_out != $uid);
	} else {
	  return $this->_data->checked_out;
	}
      }
  }

  function checkin()
  {
    if ($this->_id)
      {
	$table = & $this->getTable();
	if(! $table->checkin($this->_id)) {
	  $this->setError($this->_db->getErrorMsg());
	  return false;
	}
      }
    return false;
  }

  function checkout($uid = null)
  {
    if ($this->_id)
      {
	// Make sure we have a user id to checkout the article with
	if (is_null($uid)) {
	  $user	= &JFactory::getUser();
	  $uid	= $user->get('id');
	}
	// Lets get to it and checkout the thing...
	$table = & $this->getTable();
	if(!$table->checkout($uid, $this->_id)) {
	  $this->setError($this->_db->getErrorMsg());
	  return false;
	}

	return true;
      }
    return false;
  }

  function store($data)
  {     
    // First check the data fields:
    $row =& $this->getTable();
      
    // Bind the form fields to the web link table
    if (!$row->bind($data)) {
      $this->setError($this->_db->getErrorMsg());
      return false;
    }

    // if new item, order last in appropriate group

    if (!$row->id) {
      $user = & JFactory::getUser();
      
      $row->ordering = $row->getNextOrder();
      $row->created = gmdate('Y-m-d H:i:s');
      $row->created_by = $user->id;      
    }
    else {      
      $this->_db->setQuery(
			   sprintf(
				   'UPDATE #__geoarticle SET ordering = ordering+1 WHERE ordering >= %d ',
				   (int) $row->ordering
				   )
			   );

      if (!$this->_db->query()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
      }
    }

    // Make sure the table is valid
    if (!$row->check()) {
      $this->setError($this->_db->getErrorMsg());
      return false;
    }

    // Now Store the record to the database
    if (!$row->store()) {
      $this->setError($this->_db->getErrorMsg());
      return false;
    }
        
    if (!$row->reorder()) {
      $this->setError($this->_db->getErrorMsg());
      return false;
    }

    return true;
  }


  function delete($gaid = array())
  {
    $result = false;

    if (count( $gaid ))
      {
	JArrayHelper::toInteger($gaid);
	$gaids = implode( ',', $gaid );
			
	// First the associations
	$this->_db->setQuery( 'DELETE FROM #__content_geoarticle WHERE gaid IN ( '.$gaids.' )' );
	if(!$this->_db->query()) {
	  $this->setError($this->_db->getErrorMsg());
	  return false;
	}
      
	// Then the tags:
	$this->_db->setQuery( 'DELETE FROM #__geoarticle WHERE id IN ( '.$gaids.' )' );
	if(!$this->_db->query()) {
	  $this->setError($this->_db->getErrorMsg());
	  return false;
	}
            
      }

    return true;
  }

  function publish($gaid = array(), $publish = 1)
  {
    $user	=& JFactory::getUser();

    if (count( $gaid ))
      {
	JArrayHelper::toInteger($gaid);

	$this->_db->setQuery(
			     sprintf(
				     'UPDATE #__geoarticle SET state = %d WHERE id IN ( %s ) AND ( checked_out = 0 OR ( checked_out = %d ) )',
				     (int) $publish,
				     implode( ',', $gaid ),
				     (int) $user->get('id')
				     )
			     );
      
	if (!$this->_db->query()) {
	  $this->setError($this->_db->getErrorMsg());
	  return false;
	}
      }

    return true;
  }

  function move($direction)
  {
    $row =& $this->getTable();
    if (!$row->load($this->_id)) {
      $this->setError($this->_db->getErrorMsg());
      return false;
    }

    if (!$row->move( $direction ) ) {
      $this->setError($this->_db->getErrorMsg());
      return false;
    }

    return true;
  }


  function _loadData()
  {
    // Lets load the content if it doesn't already exist
    if (empty($this->_data))
      {               
	$this->_db->setQuery(
			     sprintf(
				     'SELECT ga.* FROM #__geoarticle AS ga  WHERE ga.id = %d',
				     (int) $this->_id
				     )
			     );
      
	$this->_data = $this->_db->loadObject();
	return (boolean) $this->_data;
      }
    return true;
  }

  /**
   * Method to initialise the data
   */
  function _initData()
  {
    // Lets load the content if it doesn't already exist
    if (empty($this->_data))
      {
	$record = new stdClass();
	$record->id          = 0;
	$record->title       = null;
	$record->description = null;
	$record->ordering    = 0;
	$record->state       = 0;
	$record->created     = JFactory::getDate()->toFormat('%Y-%m-%d %H:%M:%S');
	$record->created_by  = null;
         
	$record->checked_out       = 0;
	$record->checked_out_time  = 0;

	$this->_data = $record;
	return (boolean) $this->_data;
      }
    return true;
  }
}